package com.cy.aircompressor.main.home;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.cy.aircompressor.AppManager;
import com.cy.aircompressor.R;
import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.ActivityMainBinding;
import com.cy.aircompressor.entity.select.SelectDict;
import com.cy.aircompressor.entity.system.SysConfig;
import com.cy.aircompressor.entity.system.UserInfo;
import com.cy.aircompressor.main.home.dialog.ModifyPwdDialog;
import com.cy.aircompressor.main.home.viewmodel.MianViewModel;
import com.cy.aircompressor.main.ui.Infoover.fragment.InformationOverviewFragment;
import com.cy.aircompressor.main.ui.dataanalysis.fragment.DataAnalysisFragment;
import com.cy.aircompressor.main.ui.lifecycle.fragment.LifeCycleFragment;
import com.cy.aircompressor.main.ui.onlinemonitor.fragment.OnlineMonitorFragment;
import com.cy.aircompressor.main.home.other.WarningFragment;
import com.cy.aircompressor.main.ui.systemsetting.fragment.SystemSettingFragment;
import com.cy.aircompressor.main.view.BottomBar;
import com.cy.aircompressor.main.view.BottomBarTab;
import com.cy.aircompressor.main.view.pop.ExitPopupWindow;
import com.cy.aircompressor.main.welcome.LoginActivity;
import com.drug.lib.util.DLog;
import com.drug.lib.util.SPManager;
import com.drug.lib.util.ToastUtil;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.Resource;
import com.net.model.base.activity.BaseVMActivity;
import com.net.model.livedatas.LiveDataBus;
import com.net.model.utils.Constant;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * 类知乎 复杂嵌套Demo tip: 多使用右上角的"查看栈视图"
 * Created by YoKeyword on 16/6/2.
 */
public class MainActivity extends BaseVMActivity<ActivityMainBinding, MianViewModel> {
    SupportFragment currentFragment;
    private List<SupportFragment> fragments = new ArrayList<>();
    private int ready = 0;
    private ModifyPwdDialog modifyPwdDialog;
    public static void start(Context activity) {
        Intent intent = new Intent();
        intent.setClass(activity, MainActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected ActivityMainBinding getViewBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
//        mViewModel.currentUserInfo();
        mViewModel.compressorPart();
        mViewModel.compressor();
        initView();
        resumeFragments();
        initFragments();
        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mViewModel.queryConfig();
                mViewModel.queryWarningCount();
                mViewModel.compressorPoint();
                mViewModel.collectorChannel();
                mViewModel.powerStation();
                mViewModel.sensorRange();
                mViewModel.sensorType();
            }
        }, 1000);
//        long start = System.currentTimeMillis();
//        int uid = UsageUtil.getUidByPackageName(mContext, getApplication().getPackageName());
//
//        getHandler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                long end = start + 60000;
//                DLog.d("uid==="+uid);
//                DLog.d("start=时间=="+start);
//                DLog.d("end=时间=="+end);
//                Usage usage0 = UsageUtil.getUsageBytesByUid(mContext, start, end, uid);
//                DLog.d("getUsageBytesByUid-当前统计数据展示：" + usage0.toString());
//                Usage usage = UsageUtil.getApplicationQueryDetails(mContext, start, end, uid);
//                DLog.d("QueryDetails-当前统计数据展示：" + usage.toString());
//                Usage usage2 = UsageUtil.getApplicationQuerySummary(mContext, start, end, uid);
//                DLog.d("QuerySummary-当前统计数据展示：" + usage2.toString());
//            }
//        }, 60000);

    }


    private void resumeFragments() {
        SupportFragment firstFragment = findFragment(InformationOverviewFragment.class);
        if (firstFragment != null) {
            // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题
            // 这里我们需要拿到mFragments的引用
            fragments.add(firstFragment);
            fragments.add(findFragment(OnlineMonitorFragment.class));
            fragments.add(findFragment(DataAnalysisFragment.class));
            fragments.add(findFragment(LifeCycleFragment.class));
            fragments.add(findFragment(SystemSettingFragment.class));
        }
    }

    private void initFragments() {
//        if (++ready < 3) return;
        SupportFragment firstFragment = findFragment(InformationOverviewFragment.class);
        if (firstFragment != null) return;
        fragments.add(InformationOverviewFragment.newInstance());
        fragments.add(OnlineMonitorFragment.newInstance());
        fragments.add(DataAnalysisFragment.newInstance());
        fragments.add(LifeCycleFragment.newInstance());
        fragments.add(SystemSettingFragment.newInstance());
        currentFragment = fragments.get(0);
        loadMultipleRootFragment(R.id.fl_container, 0,
                fragments.get(0),
                fragments.get(1),
                fragments.get(2),
                fragments.get(3),
                fragments.get(4));
    }

    private void initView() {
        mBinding.bottomBar
                .addItem(new BottomBarTab(mContext, R.drawable.nav_xxzl_bg, getString(R.string.nav_xxzl)))
                .addItem(new BottomBarTab(mContext, R.drawable.nav_zxjc_bg, getString(R.string.nav_zxjc)))
                .addItem(new BottomBarTab(mContext, R.drawable.nav_sjfx_bg, getString(R.string.nav_sjfx)))
                .addItem(new BottomBarTab(mContext, R.drawable.nav_smzqgl_bg, getString(R.string.nav_smzqgl)))
                .addItem(new BottomBarTab(mContext, R.drawable.nav_xtsz_bg, getString(R.string.nav_xtsz)));
        mBinding.bottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                showHideFragment(fragments.get(position), fragments.get(prePosition));
                currentFragment = fragments.get(position);
            }

            @Override
            public void onTabUnselected(int position) {
            }

            @Override
            public void onTabReselected(int position) {
                DLog.d("=onTabReselected===position=====" + position);
                final SupportFragment currentFragment = fragments.get(position);
                int count = currentFragment.getChildFragmentManager().getBackStackEntryCount();
                // 如果不在该类别Fragment的主页,则回到主页;
                DLog.d("=onTabReselected===count=====" + count);
//                if (count > 1) {
//                    if (currentFragment instanceof XxzlFragment) {
//                    } else if (currentFragment instanceof ZxjcFragment) {
//                        currentFragment.popToChild(RealTimeDataFragment.class, false);
//                    } else if (currentFragment instanceof SjfxFragment) {
//                        currentFragment.popToChild(PressureAnalysisFragment.class, false);
//                    } else if (currentFragment instanceof SmzqFragment) {
//                        currentFragment.popToChild(ExecutiveMaintenanceFragment.class, false);
//                    }else if (currentFragment instanceof XtszFragment) {
//                        currentFragment.popToChild(DisplayInformationFragment.class, false);
//                    }
//                    return;
//                }


                // 这里推荐使用EventBus来实现 -> 解耦
//                if (count == 1) {
//                    // 在FirstPagerFragment中接收, 因为是嵌套的孙子Fragment 所以用EventBus比较方便
//                    // 主要为了交互: 重选tab 如果列表不在顶部则移动到顶部,如果已经在顶部,则刷新
//                    EventBusActivityScope.getDefault(MainActivity.this).post(new TabSelectedEvent(position));
//                }
            }
        });

        RxView.clicks(mBinding.messageLy)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    WarningFragment.showDialogFragment(getSupportFragmentManager(), "2", null);
                });
        RxView.clicks(mBinding.userInfoLayout)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    List<SelectDict> selectDicts = new ArrayList<>();
                    SelectDict selectDict = new SelectDict();
                    selectDict.setLabel("修改密码");
                    selectDict.setValue("modify_password");
                    selectDicts.add(selectDict);
                    selectDict = new SelectDict();
                    selectDict.setLabel("退出登录");
                    selectDict.setValue("exit_login");
                    selectDicts.add(selectDict);
                    ExitPopupWindow exitPopupWindow = new ExitPopupWindow(mContext, mBinding.userInfoLayout, selectDicts);
                    exitPopupWindow.showAsBelow(mBinding.userInfoLayout, 0, 5);
                    exitPopupWindow.setDropdownCallBack(new ExitPopupWindow.DropdownCallBack() {
                        @Override
                        public void select(SelectDict selectDict) {
                            if (TextUtils.equals(selectDict.getValue(), "modify_password")) {
                                modifyPwdDialog = ModifyPwdDialog.showDialogFragment(getSupportFragmentManager(), "Modify");
                                modifyPwdDialog.setModifyPwdCallBack(new ModifyPwdDialog.ModifyPwdCallBack() {
                                    @Override
                                    public void result(Object object) {
                                        mViewModel.updatePwd(object);
                                    }
                                });
                            } else if (TextUtils.equals(selectDict.getValue(), "exit_login")) {
                                showDialog();
                            }
                        }
                    });
                });
    }

    private void showDialog() {
        new MaterialDialog.Builder(mContext)
                .title("提示")
                .content("您确定退出当前登录？")
                .positiveText("退出登录")
                .negativeText("取消")
                .canceledOnTouchOutside(false)
                .contentColor(ContextCompat.getColor(mContext, R.color.text_color_lg))
                .titleColor(ContextCompat.getColor(mContext, R.color.colorAccent))
                .backgroundColor(ContextCompat.getColor(mContext, R.color.default_background))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mViewModel.logout();
                        dialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onBackPressedSupport() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            if (currentFragment instanceof InformationOverviewFragment) {   // 如果是 第一个Fragment 则退出app
                finish();
            } else {                                    // 如果不是,则回到第一个Fragment
                mBinding.bottomBar.setCurrentItem(0);
            }
        }
    }

    MaterialDialog materialDialog;

    @Override
    protected void dataChange() {
        LiveDataBus.get("invalid-token", Integer.class).observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (integer == Constant.CODE_AUTH_FAIL) {
                    if (materialDialog != null && materialDialog.isShowing())
                        return;
                    materialDialog = new MaterialDialog.Builder(mContext)
                            .title("提示")
                            .content("由于长时间未使用，登陆已失效，请重新登录！")
                            .positiveText("去登陆")
                            .negativeText("退出系统")
                            .canceledOnTouchOutside(false)
                            .contentColor(ContextCompat.getColor(mContext, R.color.white))
                            .titleColor(ContextCompat.getColor(mContext, R.color.white))
                            .backgroundColor(ContextCompat.getColor(mContext, R.color.default_background))
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    LoginActivity.start(mContext);
                                    SPManager.removeACCOUNTMMKV();
                                    AirConfig.get().release();
                                    finish();
                                }
                            })
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    AppManager.getAppManager().appExit(mContext);
                                }
                            })
                            .show();

                }
            }

        });
        mViewModel.getUpdatePwdObservable().observe(this, new Observer<Resource<Object>>() {
            @Override
            public void onChanged(Resource<Object> objectResource) {
                objectResource.handler(new OnCallback<Object>() {
                    @Override
                    public void onSuccess(Object data) {
                        ToastUtil.show("更新完成");
                        if (modifyPwdDialog != null)
                            modifyPwdDialog.dismiss();
                    }
                });
            }
        });
        mViewModel.getLogoutObservable().observe(this, new Observer<Resource<Object>>() {
            @Override
            public void onChanged(Resource<Object> objectResource) {
                objectResource.handler(new OnCallback<Object>() {
                    @Override
                    public void onSuccess(Object data) {
                        AirConfig.get().updateLoginFlag(false);
                        SPManager.removePassword();
                        LoginActivity.start(mContext);
                        finish();
                    }
                });
            }
        });
        mViewModel.getUserInfoObservable().observe(this, new Observer<Resource<UserInfo>>() {
            @Override
            public void onChanged(Resource<UserInfo> userInfoResource) {
                userInfoResource.handler(new OnCallback<UserInfo>() {
                    @Override
                    public void onSuccess(UserInfo data) {
                        AirConfig.get().updateUserInfo(data);
                        mBinding.etUsername.setText(data.getName());
//                        initFragments();
                    }

                });
            }
        });

        mViewModel.getSysConfigObservable().observe(this, new Observer<Resource<SysConfig>>() {
            @Override
            public void onChanged(Resource<SysConfig> sysConfigResource) {
                sysConfigResource.handler(new OnCallback<SysConfig>() {
                    @Override
                    public void onSuccess(SysConfig data) {
                        AirConfig.get().updateSysConfig(data);
                        Glide.with(mContext)
                                .load(data.getSysLogo())
                                .into(mBinding.systemLogo);
                        mBinding.systemName.setText(data.getSysName());
                    }
                });
            }
        });
        mViewModel.getWarningObservable().observe(this, new Observer<Resource<Integer>>() {
            @Override
            public void onChanged(Resource<Integer> integerResource) {
                integerResource.handler(new OnCallback<Integer>() {
                    @Override
                    public void onSuccess(Integer data) {
                        mBinding.warningNum.setText(data.intValue() + "");
                    }
                });
            }
        });


        mViewModel.getPartObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateCompressorPart(data);
//                        initFragments();
                    }
                });
            }
        });

        mViewModel.getPointObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateCompressorPoint(data);
                    }
                });
            }
        });
        mViewModel.getCollectorChannelObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateCollectorChannels(data);
                    }
                });
            }
        });
        mViewModel.getCompressorObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateCompressors(data);
//                        initFragments();
                    }
                });
            }
        });
        mViewModel.getPowerStationObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updatePowerStations(data);
                    }
                });
            }
        });
        mViewModel.getSensorRangeObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateSensorRanges(data);
                    }
                });
            }
        });
        mViewModel.getSensorTypeObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateSensorTypes(data);
                    }
                });
            }
        });
    }
}
